<?php
//迭代器类和基类示例

//ObjectIterator具有Iterator接口所要求的一系列函数
//使用Iterator类的原因，即使内部实现发生变化，数据接口还是不会发生变化
class ObjectIterator implements Iterator {

    private $obj;
    private $count;
    private $currentIndex;

    //构造函数，初始化任务
    function _construct($obj)
    {
        $this->obj = $obj;
        $this->count = count($this->obj->data);
    }

    //将内部数据指针设置回数据开始处
    function rewind()
    {
        $this->currentIndex = 0;
    }

    //判断数据指针的当前位置是否还存在更多数据
    function valid()
    {
        return $this->currentIndex < $this->count;
    }

    //返回数据指针值
    function key()
    {
        return $this->currentIndex;
    }

    //返回
    function current()
    {
        return $this->obj->data[$this->currentIndex];
    }

    //在数据中移动数据指针的位置
    function next()
    {
        $this->currentIndex++;
    }
}

    //子类继承
    class Objects implements IteratorAggregate
    {
        public $data = array();

        function _construct($in)
        {
            $this->data = $in;
        }

        function getIterator()
        {
            return new ObjectIterator($this);
        }
    }

    $myObject = new Objects(array(2, 4, 6, 8, 10));

    $myIterator = $myObject->getIterator();
    for($myIterator->rewind(); $myIterator->valid(); $myIterator->next())
    {
        $key = $myIterator->key();
        $value = $myIterator->current();
        echo $key." => ".$value."<br />";
    }
?>